from random import Random
import sys
import string
import pwd
import pexpect
import file as manage
#from file import process_dir

def main():
    user = sys.argv[1]
    password = sys.argv[2]
    if exist_user(user):
        print get_user_id(user)
        print get_group_id(user)
        print set_user_password(user, password)
#    process_user(user,'apache','/var/www/home','/sbin/nologin')

def get_user_id (username):
    try:
        user = pwd.getpwnam(username)
        return user.pw_uid
    except KeyError:
        return -1

def get_group_id(username):
    try:
        user = pwd.getpwnam(username)
        return user.pw_gid
    except KeyError:
        return -1

def exist_user(username):
    if get_user_id(username) == -1:
        return False
    else:
        return True

def add_user(username,groupname,home,shell):
    if not exist_user(username):
        return False
    (output,exitstatus) = pexpect.run("useradd -d "+home+" -g "+groupname+" -s "+shell+" "+username, withexitstatus=1)
    if exitstatus == 0:
        return True
    else:
        return False

def delete_user(username):
    if not exist_user(username):
        return False
    (output,exitstatus) = pexpect.run("userdel  "+username, withexitstatus=1)
    if exitstatus == 0:
        return True
    else: 
        return False

def set_user_password(username,password):
    if not exist_user(username):
        return False
    child = pexpect.spawn("passwd", [username], env={ "LANG" : "C"})
    child.expect("New UNIX password")
    child.sendline(password)
    child.expect("Retype new UNIX password")
    child.sendline(password)
    child.expect("password updated successfully")
    child.close()
    if child.exitstatus == 0:
        return True    
    else:
        return False

def generate_password():
        passwdChars = string.letters + string.digits
        passwdLength = Random().sample([10, 11, 12], 1).pop()
        return ''.join(Random().sample(passwdChars, passwdLength))

def process_user(username,groupname,basedir,shell):
    home = basedir+'/'+username
    sitehome = home+'/www/'
    if not exist_user(username):
        if not add_user(username, groupname, basedir, shell):
            return False
    if manage.process_dir(home, username, groupname, '0750'):
        if manage.process_dir(sitehome, username, groupname, '0750'):
            return True
    return False

if __name__ == "__main__":
        main()
